package ua.senfiron.finder;

import java.util.Arrays;
import java.util.List;

import ua.senfiron.finder.SearchTaskFragment.SearchTaskCallbacks;
import ua.senfiron.finder.searchengine.BingWebSearchEngine;
import ua.senfiron.finder.searchengine.GoogleCustomSearchEngine;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements SearchTaskCallbacks {
    public static final String LAST_SEARCH_QUERY = "last_search_query";
    private LinearLayout mQueryControls;
    private LinearLayout mProgressControls;
    private EditText mEditTextQuery;
    private ProgressBar mProgressBar;
    private TextView mProgressText;
    private SearchResultItemAdapter mAdapter;
    private SearchTaskFragment mSearchTaskFragment;
    private List<SearchResultItem> mItems = null;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //Viewless fragment for Search work
        FragmentManager fm = getSupportFragmentManager();
        mSearchTaskFragment = (SearchTaskFragment) fm.findFragmentByTag("task");

        // If the Fragment is non-null, then it is currently being
        // retained across a configuration change.
        if (mSearchTaskFragment == null) {
          mSearchTaskFragment = new SearchTaskFragment();
          fm.beginTransaction().add(mSearchTaskFragment, "task").commit();
          
          //TODO: Add SearchEngine selection to settings
          mSearchTaskFragment.addSearchEngine(new BingWebSearchEngine());
          mSearchTaskFragment.addSearchEngine(new GoogleCustomSearchEngine());

        }
        mItems = mSearchTaskFragment.getItems();
        
        mQueryControls = (LinearLayout) findViewById(R.id.layoutQueryControls);
        mProgressControls = (LinearLayout) findViewById(R.id.layoutProgressControls);
        mEditTextQuery = (EditText) findViewById(R.id.editTextQuery);
        mProgressBar = (ProgressBar) findViewById(R.id.progressBarSearchProgress);
        mProgressText = (TextView) findViewById(R.id.textViewProgressText);
        
        if(mSearchTaskFragment.isSearchRunning())
        {
            mQueryControls.setVisibility(View.GONE);
            mProgressControls.setVisibility(View.VISIBLE);
            
            mProgressBar.setMax(mSearchTaskFragment.getTotalRequestedQuantity());
            mProgressBar.setProgress(mItems.size());
        }
        
        //Load last used keywords to EditText
        SharedPreferences settings = getSharedPreferences(LAST_SEARCH_QUERY, 0);
        String lastSearchQuery = settings.getString("lastSearchQuery", "");
        mEditTextQuery.setText(lastSearchQuery);
        mEditTextQuery.setOnEditorActionListener(new OnEditorActionListener() {

            public boolean onEditorAction(TextView v, int actionId,
                    KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    startSearch(v);
                    handled = true;
                }
                return handled;
            }
        });
        
        mAdapter = new SearchResultItemAdapter(mItems);

        ListView listView = (ListView) findViewById(R.id.listViewSearchResults);
        listView.setAdapter(mAdapter);
        
        //Open browser on search result item clicked
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position,
                    long id) {
                SearchResultItem item = (SearchResultItem) mItems.get(position);
                Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(item.getUrl()));
                startActivity(browserIntent);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.action_settings:
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    public void startSearch(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mEditTextQuery.getWindowToken(), 0);
        
        //Load preferences
        
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        
        mSearchTaskFragment.clearSearchEngines();
        if(pref.getBoolean("use_bing_web_search", true))
            mSearchTaskFragment.addSearchEngine(new BingWebSearchEngine());
        if(pref.getBoolean("use_google_custom_search", true))
            mSearchTaskFragment.addSearchEngine(new GoogleCustomSearchEngine());
        
        String strMaxResults = pref.getString("max_results", "300");
        int maxResults = Integer.parseInt(strMaxResults);
        mSearchTaskFragment.setMaxResults(maxResults);
        
        String query = mEditTextQuery.getText().toString();
        
        //Save keywords to SharedPreferences
        SharedPreferences settings = getSharedPreferences(LAST_SEARCH_QUERY, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("lastSearchQuery", query);
        editor.commit();
        
        if(!isNetworkConnected())
        {
            Builder alert = new AlertDialog.Builder(this);
            //alert.setTitle("");
            alert.setMessage(R.string.main_activity_internet_not_avaliable);
            alert.setPositiveButton("OK", null);
            alert.create();
            alert.show();
            hideProgressControls();
            return;
        }
        
        mItems.clear();
        mAdapter.notifyDataSetChanged();
        mProgressBar.setMax(0);
        mProgressBar.setProgress(0);
        mProgressText.setText("");

        mSearchTaskFragment.startSearch(query);
        
        mQueryControls.setVisibility(View.GONE);
        mProgressControls.setVisibility(View.VISIBLE);
    }
    
    public void hideProgressControls()
    {
        mQueryControls.setVisibility(View.VISIBLE);
        mProgressControls.setVisibility(View.GONE);
    }
    
    public void stopSearch(View view) {
        mSearchTaskFragment.stopSearch();
        hideProgressControls();
    }

    
    private boolean isNetworkConnected() {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo i = connManager.getActiveNetworkInfo();
        if (i != null && i.isConnected() && i.isAvailable())
           return true;
        return false;
    }

    @Override
    public void onProgressUpdate(SearchResultItem... results) {

        if(results != null)
        {
            mItems.addAll(Arrays.asList(results));
            mAdapter.notifyDataSetChanged();
        }

        mProgressBar.setProgress(mItems.size());        
        mProgressText.setText(getResources().getString(R.string.main_activity_progress_text_loaded)
                + " " + mItems.size()
                + " " + getResources().getString(R.string.main_activity_progress_text_of)
                + " " + mProgressBar.getMax());
    }

    @Override
    public void onPostExecute(Integer result) {
        hideProgressControls();
        Toast.makeText(this, 
                "Found " + String.valueOf(result) + " results", 
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onExpectedQuantityChanged(int difference) {
        mProgressBar.setMax(mProgressBar.getMax() + difference);
    }
}
